package main

import (
	"fmt"
	"time"
)

func main() {
	bar := new(Bar)
	bar.NewOptionWithGraph(30, 100, "=")
	bar.Play()
}

type Bar struct {
	percent uint          // 百分比
	cur     uint          // 当前进度
	total   uint          // 总进度
	rate    string        // 进度条
	graph   string        // 进度条字符
	du      time.Duration // 时间间隔
}

func (b *Bar) NewOption(start, total uint) {
	b.cur = start
	b.total = total

	if b.graph == "" {
		b.graph = "■"
	}

	if b.du == 0 {
		b.du = 100 * time.Millisecond
	}

	b.percent = b.getPercent()

	for i := 0; i < int(b.percent); i += 2 {
		b.rate += b.graph
	}
}

func (b *Bar) getPercent() uint {
	return uint(float32(b.cur) / float32(b.total) * 100)
}

func (b *Bar) NewOptionWithGraph(start, total uint, graph string) {
	b.graph = graph
	b.NewOption(start, total)
}

func (b *Bar) Play() {

	for i := b.cur; i <= b.total; i++ {
		time.Sleep(b.du)
		b.draw(uint(i))
	}

	b.Finish()
}

func (b *Bar) draw(cur uint) {
	b.cur = cur
	last := b.percent
	b.percent = b.getPercent()

	if b.percent != last && b.percent%2 == 0 {
		b.rate += b.graph
	}

	// %- 向左对齐 宽度50字符
	fmt.Printf("\r[%-50s] %3d%% %8d/%d", b.rate, b.percent, b.cur, b.total)
}

// 换行结束
func (*Bar) Finish() {
	fmt.Println()
}
